package com.yuyou.tas.lesson.controller;

import com.yuyou.tas.lesson.service.IBaseChapterService;
import com.yuyou.tas.lesson.service.IBaseLevelService;
import com.yuyou.tas.lesson.service.IBaseSectionService;
import com.yuyou.tas.lesson.service.IBaseTermService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.lesson.vo.req.ReqAddBaseChapter;
import com.yuyou.tas.lesson.vo.req.ReqUpdateBaseChapter;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseChapter;
import com.yuyou.tas.service.api.lesson.entity.BaseChapter;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.config.SystemConfig;
import com.yuyou.tas.util.enums.OrganLimitEnums;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value="BaseChapterController",description="讲次库操作接口")
@Validated
@RestController
@RequestMapping(value="/api/baseChapter")
public class BaseChapterController extends BaseController {

    @Autowired
    private IBaseChapterService service;

    @Autowired
    private OrganLimitService organLimitService;

    @Autowired
    private IBaseSectionService baseSectionService;

    @Autowired
    private IBaseLevelService levelService;

    @Autowired
    private IBaseTermService termService;

    @ApiOperation(value="插入讲次库讲次")
    @RequestMapping(value="/addBaseChapter",method = RequestMethod.POST)
    public ReturnResult addBaseChapter(HttpServletRequest request , @Validated @ModelAttribute ReqAddBaseChapter chapter){
        LoginRedisObj user = this.getUserObj(request);
        ResBoolSimpleInfo info =  service.addChapter(chapter,null,null,
                                                    user.getIsSystem()?1:0,
                                                    user,user.getOrganizationId());
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value="通过ID获取讲次库讲次")
    @RequestMapping(value="/getBaseChapter",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<BaseChapter> getBaseChapter(HttpServletRequest request ,
                                                    @Validated @NotNull(message = "ID不能为空")@ApiParam(value = "讲次库讲次ID" , required = true) @RequestParam(value = "id") Long id) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        /*if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_chapter);
        }*/
        ResBoolSimpleInfo<BaseChapter> info =  service.getChapterByID(id);
        //系统课程、但用户非系统管理员且所在机构没有对应科目年级权限
        if(info.getData() != null && !user.getIsSystem() && info.getData().getAuthOrganizationId().equals(SystemConfig.SYS_ORGAN_ID)
                && (user.getOrganSubSecMap() == null
                || !user.getOrganSubSecMap().containsKey(info.getData().getDataSubject())
                || CollectionUtils.isEmpty(user.getOrganSubSecMap().get(info.getData().getDataSubject()))
                || !user.getOrganSubSecMap().get(info.getData().getDataSubject()).contains(info.getData().getBaseSectionId()))) {
            return ReturnResult.returnRes(true , null , null);
        }
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , info.getData());
    }

    @ApiOperation(value="更新讲次库讲次")
    @RequestMapping(value="/updateBaseChapter",method = RequestMethod.POST)
    public ReturnResult updateBaseChapter(HttpServletRequest request ,
                                          @Validated @ModelAttribute ReqUpdateBaseChapter chapter) throws Exception{
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), chapter.getId(), OrganLimitEnums.type.base_chapter);
        }
        ResBoolSimpleInfo info =  service.updateChapter(chapter,null,null, user.getIsSystem()?1:0,user);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value="删除讲次库讲次")
    @RequestMapping(value="/delBaseChapter",method = RequestMethod.POST)
    public ReturnResult delBaseChapter(HttpServletRequest request ,
                                       @Validated @NotNull(message = "ID不能为空")@ApiParam(value = "讲次库讲次ID" , required = true) @RequestParam(value = "id") Long id) throws Exception {
        LoginRedisObj user = this.getUserObj(request);
        if(!user.getIsSystem()) {
            organLimitService.checkOrganByOrganId(user.getOrganizationId(), id, OrganLimitEnums.type.base_chapter);
        }
        ResBoolSimpleInfo info =  service.delChapter(id);
        return ReturnResult.returnRes(info.isSuccess() , info.getMessage() , null);
    }

    @ApiOperation(value = "分页查询讲义库讲次")
    @RequestMapping(value = "/findBaseChapterPage" ,method = {RequestMethod.GET,RequestMethod.POST})
    public ReturnResult<DtoBaseChapter> findBaseChapterPage(HttpServletRequest request,
                                                          @Validated @ModelAttribute PageParams pageParams,
                                                          @ApiParam(value = "名称")@RequestParam(value = "name",required = false) String name,
                                                          @ApiParam(value = "科目ID")@RequestParam(value = "subjectId",required = false) String dataSubject,
                                                          @ApiParam(value = "年级ID，单个")@RequestParam(value = "sectionId",required = false) String baseSectionId,
                                                          @ApiParam(value = "层级ID")@RequestParam(value = "baseLevelId",required = false) String baseLevelId,
                                                          @ApiParam(value = "学期ID")@RequestParam(value = "baseTrimesterId",required = false) String baseTrimesterId,
                                                            @ApiParam(value = "讲次类型")@RequestParam(value = "type" ,required = false) String type,
                                                            @ApiParam(value = "获取系统数据：1、是，0或不传、否")@RequestParam(value = "getSys" , required = false)Integer getSys){
        Map<String, Object> conditions = new HashMap<>();
        Pagination<DtoBaseChapter> queryPgn = new Pagination<>();
        LoginRedisObj user = this.getUserObj(request);


        if(!StringUtils.isEmpty(name)){
            conditions.put("name", name.trim());
        }

        if(!StringUtils.isEmpty(type)){
            conditions.put("type", type.trim());
        }
        if(!StringUtils.isEmpty(dataSubject)){
            conditions.put("dataSubject", dataSubject.trim());
        }/*else if(!user.getIsManager() && user.getUserType()==AuthUserEnums.type.teaching.getValue()){//教研
            conditions.put("subjectIDs", user.getDataSubjects());//获取用户科目权限
        }*/

        if(!StringUtils.isEmpty(baseSectionId)){
            conditions.put("baseSectionId", baseSectionId.trim());
        }/*else if(!user.getIsManager()){
            conditions.put("sectionIDs", user.getBaseSectionIds());//获取用户年级权限
        }*/

        if(!StringUtils.isEmpty(baseLevelId)){
            conditions.put("baseLevelId", baseLevelId.trim());
        }
        if(!StringUtils.isEmpty(baseTrimesterId)){
            conditions.put("baseTrimesterId", baseTrimesterId.trim());
        }

        if(!user.getIsManager() && user.getUserType()==AuthUserEnums.type.teaching.getValue()) {//教研-用户年纪科目权限
            conditions.put("subSecLimit" , user.getUserId());
        }

        if(getSys != null && getSys == 1){
            conditions.put("organ_id", SystemConfig.SYS_ORGAN_ID);//系统机构
            if(!user.getIsSystem()){
                //非系统管理员且查询系统课程、过滤对应机构年级科目权限
                conditions.put("permit" , user.getOrganizationId());
                /*if(CollectionUtils.isEmpty(user.getOrganSubjects()) || CollectionUtils.isEmpty(user.getOrganSectionIds())){
                    return ReturnResult.success(Pagination.getZeroPage(pageParams));
                }
                conditions.put("organSubjectLimit", user.getOrganSubjects());
                conditions.put("organSectionLimit", user.getOrganSectionIds());*/
            }
        }else {
            conditions.put("organ_id", user.getOrganizationId());//查询个人所在机构的校区
        }

        queryPgn.setConditions(conditions);
        queryPgn.setPageParams(pageParams);

        int total = service.findChapterCount(queryPgn);
        queryPgn.setTotal(total);
        queryPgn.toBePage();
        if(total > 0){
            List<DtoBaseChapter> list = service.findChapterPageList(queryPgn);
            queryPgn.setList(list);
        }
        return ReturnResult.success(queryPgn);
    }
		
}
